<template>
  <div class="user-edit-container">
    <!-- Header 区域 -->
    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <!-- 用户资料 -->
    <van-cell-group class="action-card">
      <van-cell title="头像" is-link center>
        <template #default>
          <van-image
            round
            class="avatar"
            :src="pathFilter(profile.photo)"
            @click="$refs.iptFile.click()"
          />
          <!-- file 选择框 -->
          <input
            type="file"
            ref="iptFile"
            v-show="false"
            accept="image/*"
            @change="onFileChange"
          />
        </template>
      </van-cell>
      <van-cell
        title="名称"
        is-link
        :value="profile.name"
        @click="showNameDialogFn"
      />
      <van-cell
        title="性别"
        is-link
        :value="!profile.gender ? '男' : '女'"
        @click="showSheet = true"
      />
      <van-cell
        title="生日"
        is-link
        :value="profile.birthday"
        @click="showBirthFn"
      />
    </van-cell-group>
    <!-- 修改名称对话框 -->
    <van-dialog
      v-model="isShowNameDialog"
      title="修改名称"
      show-cancel-button
      :before-close="beforeClose"
      v-fofo
    >
      <van-field
        v-model.trim="inputUserName"
        autofocus
        input-align="center"
        maxlength="11"
      />
    </van-dialog>
    <!-- 日期选择器 -->
    <van-popup v-model="isShowBirth" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="confirmFn"
        @cancel="isShowBirth = false"
      />
    </van-popup>

    <!-- 性别选择 -->
    <van-action-sheet
      v-model="showSheet"
      :actions="actions"
      @select="onSelect"
      cancel-text="取消"
      description="请选择性别"
      close-on-click-action
    />
  </div>
</template>

<script>
import { getUserProfile, updatePhotoAPI, updateProfileAPI } from "@/api";
import { pathFilter, dateFilter } from "@/utils/filter";
export default {
  name: "UserEdit",
  data() {
    return {
      profile: {}, // 用户基本资料
      inputUserName: "", //修改的用户名
      isShowNameDialog: false, // 是否显示姓名弹出框
      isShowBirth: false, // 显示时间选择器
      minDate: new Date(1930, 0, 1), // 最小的可选的日期
      maxDate: new Date(), // 最大的可选日期
      currentDate: new Date(), // 当前日期
      showSheet: false, //是否显示性别选择
      actions: [{ name: "男" }, { name: "女" }],
    };
  },
  async created() {
    try {
      const res = await getUserProfile();
      // console.log(res);
      // this.$store.commit('setUser',res.data);
      this.profile = res.data;
      this.inputUserName = this.profile.name;
    } catch (error) {
      this.$toast.fail("用户信息获取失败！");
    }
  },
  methods: {
    // 图片过滤器
    pathFilter,

    //更新头像 => 文件选择方法
    async onFileChange(ev) {
      try {
        if (ev.target.files.length === 0) return; // 防止用户未选择图片
        const fd = new FormData();
        fd.append("photo", ev.target.files[0]);
        const res = await updatePhotoAPI(fd);
        this.profile.photo = res.data.photo; // 更新最新头像
      } catch (error) {
        this.$toast.fail("更新头像失败！");
      }
    },
    // 点击名字-出现弹出框
    showNameDialogFn() {
      this.isShowNameDialog = true;
    },
    // 姓名修改弹出层-关闭前方法
    async beforeClose(action, done) {
      // action的值: confirm或cancel(点击按钮区分)
      if (action === "confirm") {
        // 确定
        const reg = /^[a-zA-Z0-9\u4e00-\u9fa5]{1,7}$/;
        if (reg.test(this.inputUserName)) {
          // 通过校验 调用接口 更新页面显示的名字
          try {
            await updateProfileAPI({ name: this.inputUserName });
            this.profile.name = this.inputUserName;
          } catch (error) {
            this.$toast.fail("修改名称失败！");
          }
          // 关闭弹窗
          done();
        } else {
          // 提示用户
          this.$toast({ message: "用户名中英文和数字1-7位", position: "top" });
          // 阻止弹窗关闭
          done(false);
        }
      } else if (action === "cancel") {
        this.inputUserName = this.profile.name;
        // 取消
        done();
      }
    },
    // 弹出时间选择框
    showBirthFn() {
      this.isShowBirth = true;
      this.currentDate = new Date(this.profile.birthday); // 设置data组件默认显示时间
    },
    // 确定按钮 => 时间选择
    async confirmFn(value) {
      try {
        // 但是后台要"年-月-日"格式字符串参数值
        const date = dateFilter(value);
        await updateProfileAPI({ birthday: date });
        this.profile.birthday = date; // 前端页面同步
        this.isShowBirth = false;
      } catch (error) {
        this.isShowBirth = false;
        this.$toast.fail("修改出生日期失败！");
      }
    },
    // 修改性别
    async onSelect(val) {
      try {
        let gender = 0;
        if (val.name === "女") gender = 1;
        if(this.profile.gender === gender) return
        const res = await updateProfileAPI({ gender });
        this.profile.gender = gender;
      } catch (error) {
        this.$toast.fail("修改性别失败！");
      }

      console.log(gender, res);
    },
  },
};
</script>

<style lang="less" scoped>
.user-edit-container {
  padding-top: 46px;
  .avatar {
    width: 50px;
    height: 50px;
  }
}
</style>
